﻿using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.ObjectPool;

namespace KinonekoSoftware.Foundation
{
    public static class Pool
    {
        private static readonly ObjectPool<StringBuilder> StringBuilderPool;
        private static readonly byte[]                    SaltTable = new byte[] { 0x55, 0x96, 0x47, 0x19 };

        static Pool()
        {
            var objectPoolProvider = new DefaultObjectPoolProvider();
            StringBuilderPool = objectPoolProvider.CreateStringBuilderPool(32, 128);
        }

        public static string Md5(byte[] buffer)
        {
            var base64Byte = MD5.ComputeHash(buffer);
            return Convert.ToBase64String(base64Byte);
        }
        
        public static string Md5(MemoryStream buffer)
        {
            var base64Byte = MD5.ComputeHash(buffer);
            return Convert.ToBase64String(base64Byte);
        }
        
        
        
        public static string Salt(string pwd)
        {
            var utf8  = Encoding.UTF8.GetBytes(pwd);
            var step1 = MD5.ComputeHash(utf8);
            var step2 = new byte[utf8.Length + 4];
            
            Array.Copy(step1, step2, utf8.Length);
            Array.Copy(SaltTable, 0, step2, utf8.Length, 4);

            return Convert.ToBase64String(step2);
        }

        public static StringBuilder GetStringBuilder() => StringBuilderPool.Get();
        
        public static void Return(StringBuilder sb)
        {
            sb.Clear();
            StringBuilderPool.Return(sb);
        }
        public static readonly MD5  MD5  = MD5.Create();
        public static readonly SHA1 SHA1 = SHA1.Create();
    }
}